<?php

namespace App\Http\Controllers\NonPublicVersion;

use App\Http\Controllers\ErrorCode;
use App\Http\Controllers\SuccessCode;
use App\Model\AppDownload;
use App\Model\Channel;
use App\Model\ChannelLevel;
use App\Model\GameList;
use App\Model\GamePackage;
use App\Model\GameConfig;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Common;
use Ramsey\Uuid\Uuid;
use Storage;

class PackageList extends Controller
{
    use Common;
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $name = $request->input('name','');
        $channelName = $request->input('key','');
        $packageType = $request->input('package_type','APK');
        $status = $request->input('status','');
        $params = [];
        $query = [
            'name' => $name,
            'key' => $channelName,
            'package_type' => $packageType,
            'status' => $status,
        ];

        $pageSize = $request->get('paginate',config('web.page.num'));
        $pageSize = $pageSize == 0 ? config('web.page.num') : $pageSize;

        if ($name){
            $gameList = $this->remoteQuery('appLib/sdk_search_app_name',[
                'keywords' => $name
            ]);
            $gameIds = array_pluck($gameList,'app_id');
            $params['game_id']['key'] = 'game_id';
            $params['game_id']['condition'] = 'in';
            $params['game_id']['value'] = $gameIds;
        }

        if ($channelName){
            $channelIds = Channel::where('name','like',"%{$channelName}%")->where('pid','!=',0)->get()->pluck('id');
            $params['channel_id']['key'] = 'channel_id';
            $params['channel_id']['condition'] = 'in';
            $params['channel_id']['value'] = $channelIds;
        }

        if ($packageType){
            $params['type']['key'] = 'type';
            $params['type']['condition'] = '=';
            $params['type']['value'] = $packageType;
        }

        if ($status){
            $params['status']['key'] = 'status';
            $params['status']['condition'] = '=';
            $params['status']['value'] = $status;
        }

        if (!empty($params)){
            $lists = new GamePackage();
            foreach ($params as $param) {
                $lists = $param['condition'] == 'in' ?
                    $lists->whereIn($param['key'],$param['value']) :
                    $lists->where($param['key'],$param['condition'],$param['value']);
            }
            $lists = $lists->orderBy('id','DESC')->paginate($pageSize);
        } else{
            $lists = GamePackage::orderBy('id','DESC')->paginate($pageSize);
        }

        $gameIds = implode(',',$lists->pluck('game_id')->toArray());

        $gameList = $this->remoteQuery('appLib/get_app_by_ids',[
            'app_ids' => $gameIds
        ]);

        foreach ($lists as $key => $list) {
            $channel = Channel::find($list->channel_id);
            foreach ($gameList as $field => $item) {
                if ($list->game_id == $item['app_id']){
                    $lists[$key]->app_name = $item['app_name'];
                    $lists[$key]->channel_name = $channel ? $channel->name : '';
                    $lists[$key]->status = config('web.apk_package')[$list->status];
                    $lists[$key]->file_path = config('web.cdn_url') .'nonPublicVersion/gamePackage/' . $list->id;
                }
            }
        }

        $lists->totalPage = ceil($lists->total() / $pageSize);
        $lists->url = url('/nonPublicVersion/gamePackage');
        return view('nonPublicVersion.package.index',[
            'lists' => $lists,
            'pageSize' => $pageSize,
            'query' => $query
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($gameId,$game_name,$supplier_name,$platform)
    {
        $channel = Channel::where('pid','!=',0)->get();
        return view('nonPublicVersion.package.add',[
            'game_id' => $gameId,
            'game_name' => $game_name,
            'supplier_name' => $supplier_name,
            'platform' => $platform,
            'channels' =>$channel
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $gameId = $request->input('game_id','');
        $channelId = $request->input('channel_id','');
        $package_id = $request->input('package_id','');
        $channel = Channel::find($channelId);

        $gameChannelModel = GamePackage::where('game_id',$gameId)->where('channel_id',$channelId);
        $gameChannel = $gameChannelModel->first();

        if (!$channelId){
            return $this->getView([],ErrorCode::CHANNEL_ID_EMPTY);
        }

        if (!$gameId){
            return $this->getView([],ErrorCode::GAMEID_EMPTY);
        }

        $findData = GameList::where('game_id',$gameId)->first();

        if (!$findData){
            return $this->getView([],ErrorCode::GAME_CONFIG_ERROR);
        }

        $filePath = $findData->package_path;


        $filename = Storage::url('app/'.$filePath);

        if (!file_exists(base_path( 'storage/app/' .$filePath))){
            return $this->getView([],ErrorCode::FILE_NOT_EXIST);
        }

        //如果渠道已经存在 打包
        if ($gameChannel && !$package_id){//提示前端已经存在
            $id = $gameChannel->id;
            $arr = [
                'package_id'=>$id,
                'game_id' => $gameId,
                'channel_id' => $channelId
            ];
            return $this->getView($arr,ErrorCode::CHANNEL_PACKAGE_EXIST);
        } else if ($gameChannel && $package_id){
            $id = $gameChannel->id;
            $gameChannelModel->update([
                'status' => 1
            ]);
        } else {
            $data = [
                'game_id' => $gameId,
                'channel_id' => $channelId,
                'status' => 1,
                'type' => $request->input('type', 'APK'),
                'addTime' => time(),
            ];
            $id = GamePackage::insertGetId($data);
        }
        $findGameConfig = GameConfig::where('game_id', $gameId)->first();

        //打包信息
        $taskData = [
            'target_apk' => $filename,
            'dir' => 'unPackage_apk_temp_' . uniqid(),
            'channel' => $channel->unique_id,
            'new_apk_name' =>  Uuid::uuid1()->getHex() . '.apk',
            'game_id' => $id,
            //'notify_url' => 'http://zy.zhiyugame.com/Api/appLib/update_app_file_url',
            'download_url' => config('web.cdn_url') . 'nonPublicVersion/gamePackage/'.$id,
            'is_non_public' => true,
            'true_game_id' => $gameId,
            'hot_cloud_id' => $findGameConfig ? $findGameConfig->hot_cloud_id : '',
        ];

        if ( 21 == $channel->id){
            $taskData['notify_url'] = config('web.notify_zhi_app') . 'appLib/update_app_file_url';
        }

        $redis = new \Redis();
        $redis->connect(config('web.redis.host'), config('web.redis.port'));

        $taskId = $redis->Lpush("package", json_encode($taskData));

        if ($id){
            return $this->getView([],SuccessCode::ADD_SUCCESS);
        } else {
            return $this->getView([],ErrorCode::ADD_ERROR);
        }
    }

    /**
     * 游戏包文件下载
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $collect = GamePackage::find($id);

        $appDownLoad = new AppDownload();
        $appDownLoad->app_id = $collect->game_id;
        $appDownLoad->down_time = time();
        $appDownLoad->source = 2;
        $appDownLoad->save();

        if ($collect &&  file_exists(base_path($collect->file_path))){
            return response()->download(realpath(base_path($collect->file_path)));
        }
        return '游戏文件不存在';
    }

    /**
     *  打包渠道列表
     *
     * @param  int  $id 游戏ID
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $gameId = $id;
        $lists = GamePackage::where('game_id',$gameId)->paginate(config('web.page.num'));
        foreach ($lists as $key => $list){
            $channel = Channel::find($list->channel_id);
            $lists[$key]->channel_name = $channel->name;
            $lists[$key]->unique_id   = $channel->unique_id;
        }

        $lists->totalPage = ceil($lists->total() / config('web.page.num'));
        $lists->url = url('/nonPublicVersion/gamePackage' . $gameId . '/edit');

        return view('nonPublicVersion.package.channel',[
            'lists' => $lists
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $ids = request()->get('ids','');
        if ($ids){
            GamePackage::whereIn('id',explode(',',$ids))->delete();
        } else {
            if (GamePackage::find($id)){
                $res = GamePackage::destroy($id);
            }
        }
        return $this->getView([],SuccessCode::DEL_SUCCESS);
    }

    public function getChannel($id)
    {
        $channel = Channel::where('id',$id)->first();
        $one = ChannelLevel::where('id',$channel->one_channel)->first();
        $two = ChannelLevel::where('id',$channel->two_channel)->first();
        $father = Channel::where('id',$channel->pid)->first();

        return $this->getView([
            'one' =>$one ? $one->name : '',
            'two' =>$two ? $two->name : '',
            'father' =>$father ? $father->name : '',
        ],SuccessCode::GET_SUCCESS);
    }
}
